from django.shortcuts import render
from django.http import JsonResponse
from common.models import Customer,Room,RoomLog
import datetime
from django.db.models import Q
import json
import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'hotelsys.settings'
from django.core import signing

KEY = '2018211302'
SALT = 'BUPT'

def decrypt(src):
    src = signing.b64_decode(src.encode()).decode()
    raw = signing.loads(src, key=KEY, salt=SALT)
    return raw


def checkToken(token):
    # print(token)
    temp1 = token.split("|")
    temp2 = temp1[1].split(",")
    if (decrypt(temp2[0]) == temp1[0] and temp2[1] == decrypt(temp1[2])):
        return 1
    else:
        return 0

def minNums(startTime, endTime):
    '''计算两个时间点之间的秒数'''
    # 处理格式,加上秒位
    # startTime1 = startTime + ':00'
    # endTime1 = endTime + ':00'
    # 计算分钟数
    startTime2 = datetime.datetime.strptime(startTime, "%Y-%m-%d %H:%M:%S")
    endTime2 = datetime.datetime.strptime(endTime, "%Y-%m-%d %H:%M:%S")
    print(startTime2,endTime2)
    seconds = (endTime2 - startTime2).seconds
    # 来获取时间差中的秒数。注意，seconds获得的秒只是时间差中的小时、分钟和秒部分的和，并没有包含时间差的天数（既是两个时间点不是同一天，失效）
    total_seconds = (endTime2 - startTime2).total_seconds()
    # 来获取准确的时间差，并将时间差转换为秒
    print(total_seconds)
    return total_seconds

def signin(request):
    # 获取住户输入的手机号
    print(request.body)
    request.params = json.loads(request.body)
    print(request.params)
    ph = request.params['phonenumber']

    if ph:
        # 考虑输入号码不存在的情况...
        try:
            cus = Customer.objects.get(phonenumber=ph)
        except Customer.DoesNotExist:
            return JsonResponse({
                'error_code': 1,
                'msg': f'输入电话号{ph}错误，请重试...'
            })

        # 修改用户信息：state改为1，checkinDate改为当前时间
        cus.state = 1
        cus.checkinDate = datetime.datetime.now()
        # 修改房间状态：有人入住，登记入住时间，录入折扣力度
        room = Room.objects.get(rid=cus.rid_id)
        room.busy = 1
        room.discount = cus.discount
        room.checkinDate = cus.checkinDate

        # 是否需要写日志？
        # 不需要

        # 保存到数据库
        cus.save()
        room.save()

        # 返回用户入住所需信息
        return JsonResponse({'error_code': 0,
                             'data': [
                                    {
                                    'name': cus.username,
                                    'rid': cus.rid_id,
                                    'password': cus.password
                                    }
                                ]
                             })

    return JsonResponse({'error_code': 1,
                         'msg': '请输入手机号...'})

def logout(request):
    # token...
    token = request.META.get("HTTP_AUTHORIZATION")
    # 住户的token是rid:*****,checkinDate:*****
    # 分隔符...
    print(token)
    # strlist = token.split(',')
    # ridlist = strlist[0].split('|')
    # datalist = strlist[1].split('|')
    # src1 = signing.loads(ridlist[1])
    # src2 = signing.loads(datalist[1])
    # print(ridlist[0],src1['rid'])
    # print(ridlist[1],src2['checkinDate'])
    if checkToken(token):
        # print('access...')
        # 获取房间号
        request.params = json.loads(request.body)
        roomid = request.params['rid']

        if roomid:
            try:
                room = Room.objects.get(rid=roomid)
            except Room.DoesNotExist:
                return JsonResponse({
                    'error_code': 0,
                    'msg': f'房间{roomid}不存在，请重新尝试'
                })

            # 修改房间状态
            room.busy = 0

            # 记录退房时间
            room.lastCheckoutDate = datetime.datetime.now()

            if room.onoff == 1:
                # 如果住户忘记关空调，则前台关闭
                room.onoff = 0
                room.mode = None
                room.temp = None
                room.discount = None
                # 记录日志
                log = RoomLog.objects.create(optime = room.lastCheckoutDate,
                                             onoff = 0,
                                             rid = room,
                                             temp = room.temp,
                                             mode = room.mode,
                                             discount = room.discount)

            # 保存到数据库
            room.save()

            # 出具房间账单详单
            # 计算duration
            # 用户可能不止一次开关空调！！！
            # 找到checkinDate~checkoutDate之间所有该房间的onff状态列表和对应时间

            duration = 0.0
            # print(room.rid,room.checkinDate,room.lastCheckoutDate)
            loglist = RoomLog.objects.filter(Q(rid=room.rid) & Q(optime__gte=room.checkinDate) & Q(optime__lte=room.lastCheckoutDate))
            loglen = len(loglist)

            # 如果住户没有使用过空调
            if loglen == 0:
                return JsonResponse({
                    "error_code": 0,
                    "data": [
                        {
                            "duration": 0,
                            "price": 0.0,
                        }
                    ]
                })

            timetable = {}
            for i in range(loglen):
                timetable[loglist[i].optime] = loglist[i].onoff

            timekey = list(timetable.keys())
            onoffvalue = list(timetable.values())
            len1 = len(onoffvalue)
            # print(onoffvalue)
            flag = 0

            for i in range(len1):
                if flag == 0 and onoffvalue[i] == 0:
                    timetable.pop(timekey[i])
                else:
                    flag = 1
                    if onoffvalue[i] == onoffvalue[i - 1]:
                        timetable.pop(timekey[i])
            print(timetable)
            timekey = list(timetable.keys())
            len2 = len(timekey)
            print(len2)
            for i in range(0,len2,2):
                startTime = timekey[i].strftime('%Y-%m-%d %H:%M:%S')
                endTime = timekey[i+1].strftime('%Y-%m-%d %H:%M:%S')
                duration = duration + minNums(startTime,endTime)
                print(timekey[i],timekey[i+1],duration)
            duration = duration/60

            return JsonResponse({
                "error_code": 0,
                "data": [
                    {
                        "duration": int(duration),
                        "price": room.totalcost,
                    }
                ]
            })
        return JsonResponse({'error_code': 1,
                             'msg': '请出示房卡...'})
    else:
        return JsonResponse({'error_code': 1,
                             'msg': '非法访问...'})